package gl.java.sms;

import gl.java.sms.bean.Smser;
import gl.java.sms.util.Result;
import gl.java.sms.util.TextUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sun.jersey.spi.resource.Singleton;

@Path("userlist")
@Singleton
public class UserList {
	private static HashMap<String, Smser> list = new HashMap<String, Smser>();

	@GET
	public String list(@QueryParam("token") String token) {
		if (TextUtils.isEmpty(token)) {
			return Result.formatErrJson("Invalid Token");
		}
		return new Gson().toJson(list);
	}

	public static void addToUserList(Smser smser) {
		list.put(smser.getToken(), smser);
	}

	public static void removeCromUserList(Smser smser) {
		if (smser != null) {
			Smser result = list.remove(smser.getToken());
			if (result == null) {
				Logger.getLogger("UserList").info(
						"removeCromUserList fail:" + smser.getToken());
			}
		}

	}

	public static boolean isHasThisToken(String token) {
		return list.containsKey(token);
	}

	public static Smser getUser(String token) {
		return list.get(token);
	}

	public static Smser getNoBusyUser(String type) {
		try {// for sync remove
			Iterator<String> it = list.keySet().iterator();
			while (it.hasNext()) {
				Smser s = list.get(it.next());
				if (!s.isBusy()) {
					return s;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void checkSmserIsOnline() {
		try {// for sync remove
			HashSet<Smser> hadOffLineSmser = new HashSet<Smser>();
			
			Iterator<String> it = list.keySet().iterator();
			while (it.hasNext()) {
				Smser s = list.get(it.next());

				if ((System.currentTimeMillis() - s.getLastConnectTime()) > (60 * 1000)) {
					hadOffLineSmser.add(s);
				
				}
			}

			for (Smser smser : hadOffLineSmser) {
				UserList.removeCromUserList(smser);
				Logger.getLogger("UserList").info(
						"removeOfflineSmser :" + smser.getToken());
			}
			hadOffLineSmser.removeAll(hadOffLineSmser);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}